using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class GameManager : MonoBehaviour {
    public static GameManager Instance;
    private bool isGameOver;
    private float spawnTime;
    private int score;

    public GameObject gameOverPanel;
    public GameObject[] circlePrefabs;
    public Vector2 spawnRateRange;
    public TMP_Text scoreText;
    public float spawnDistance; // 生成小球与玩家的距离
    public Transform backGroundTransform;

    [HideInInspector]
    public Vector2 backgroundSize;

    void Start() {
    }

    void Update() {
        spawnTime -= Time.deltaTime;

        if (spawnTime < 0) {
            SpawnNewCircle();
            spawnTime = UnityEngine.Random.Range(spawnRateRange.x, spawnRateRange.y);
        }
    }

    private void Awake() {
        backgroundSize = GetBackgroundSize2D(backGroundTransform);
        Debug.Log($"{backgroundSize.x},{backgroundSize.y}");

        if (Instance == null) {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else {
            Destroy(gameObject);
        }

        for (int i = 0; i < 8; i++) {
            SpawnNewCircle();
        }
    }

    //抄ai的，回头查查这几个的意思
    public static Vector3 GetBackgroundSize(Transform transform) {

        //优先使用renderer的边界
        Renderer renderer = transform.GetComponent<Renderer>();
        if (renderer != null) {
            return renderer.bounds.size;
        }

        //其次使用Mesh
        MeshFilter meshFilter = transform.GetComponent<MeshFilter>();
        if (meshFilter != null) {
            Bounds localBounds = meshFilter.mesh.bounds;
            return Vector3.Scale(localBounds.size, transform.lossyScale);
        }

        //最后使用lossyScale
        return transform.lossyScale;
    }

    public static Vector2 GetBackgroundSize2D(Transform transform) {
        Vector3 size3D = GetBackgroundSize(transform);
        return new Vector2(size3D.x, size3D.y);
    }

    public void GameOver() {
        if (!isGameOver) {
            Debug.Log("GameOver");
            isGameOver = true;
            gameOverPanel.SetActive(isGameOver);
            Time.timeScale = 0;
        }
    }

    void SpawnNewCircle() {
        PlayerComponent pc = FindObjectOfType<PlayerComponent>();

        GameObject circleToSpawn = circlePrefabs[UnityEngine.Random.Range(0, circlePrefabs.Length)];

        // 在玩家周围的一个圆上随机生成
        double angle;
        Vector2 randomSpawnPos;
        int maxAttempt = 100;
        int attempt = 0;
        do {
            angle = UnityEngine.Random.Range(0, (float)(Math.PI * 2));
            randomSpawnPos = new Vector2((float)(pc.transform.position.x + Math.Sin(angle) * spawnDistance * pc.playerSize),
                                                 (float)(pc.transform.position.y + Math.Cos(angle) * spawnDistance * pc.playerSize));

            attempt++;//防止死循环
            if (attempt != 0) {
                Debug.Log($"Attempt {attempt} fail");
            }
            if (attempt == maxAttempt) {
                Debug.Log("out of attempt");
                break;
            }
        } while (Math.Abs(randomSpawnPos.x) >= backgroundSize.x / 2f
                || Math.Abs(randomSpawnPos.y) >= backgroundSize.y / 2f);//防止生成在background之外


        GameObject circle = Instantiate(circleToSpawn, randomSpawnPos, Quaternion.identity);
        circle.GetComponent<OtherCircle>().SpawnCircle(pc.playerSize);
    }

    public void ReloadGame() {
        isGameOver = false;
        gameOverPanel.SetActive(isGameOver);
        Time.timeScale = 1;
        spawnTime = UnityEngine.Random.Range(spawnRateRange.x, spawnRateRange.y);
        score = 0;
        scoreText.text = score.ToString();
        SceneManager.LoadScene(0);
    }

    public void GainScore(int amount) {
        score += amount;
        scoreText.text = score.ToString();
    }
}
